/**
* \file TCPServerSocket.cpp
* \brief TCPServerSocket definition class
* \author Edouard ROGE
* \date 12 Novembre 2013
*/

#include "TCPSocket.h"
#include "TCPServerSocket.h"

TCPServerSocket::TCPServerSocket()
{
	m_iDescriptor = socket(AF_INET, SOCK_STREAM, 0);
}

TCPServerSocket::~TCPServerSocket()
{
	Close();
}

void TCPServerSocket::Bind(uint32 _iPort)
{
	struct sockaddr_in sin = { 0 };

	sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(_iPort);
	bind(m_iDescriptor, (struct sockaddr*) &sin, sizeof(sockaddr_in));

	listen(m_iDescriptor, 64);
	//fcntl(m_iDescriptor, F_SETFL, O_NONBLOCK);
}

ITCPSocket *TCPServerSocket::AcceptConnection()
{
	int32 iSocket = accept(m_iDescriptor, NULL, NULL);
	if (iSocket > 0)
	{
		TCPSocket * pSocket = new TCPSocket();
		pSocket->m_iDescriptor = iSocket;
		return pSocket;
	}
	else
	{
		return NULL;
	}
}


void TCPServerSocket::Send(void * _pBuffer, uint32 _iSize)
{
	send(m_iDescriptor, (char*)_pBuffer, _iSize, 0);
}

void TCPServerSocket::Receive(void * _pBuffer, uint32 _iSize)
{
	recv(m_iDescriptor, (char*)_pBuffer, _iSize, 0);
}

void TCPServerSocket::Connect(const std::string & _strAddress, uint32 _iPort)
{
	/*struct sockaddr_in sin = { 0 };
	inet_pton(AF_INET, _strAddress.GetData(), &(sin.sin_addr));
	sin.sin_port = htons(_iPort);
	sin.sin_family = AF_INET;
	connect(m_iDescriptor, (struct sockaddr*)&sin, sizeof(struct sockaddr_in));*/
}

void TCPServerSocket::Close()
{
	close(m_iDescriptor);
}